//
//  CommonCardViewController.m
//  QRMaster
//
//  Created by lc on 16/5/27.
//  Copyright © 2016年 myApple. All rights reserved.
//

#import "CommonCardViewController.h"
#import "TotalCardCell.h"
#import "RequestNetWork.h"
#import "OpertionPlist.h"
#import "CardInfoModel.h"
#import "FloorsModel.h"
#import "roomsModel.h"
#import "checkPower.h"
#import "QRSingleton.h"
#import "RoomCardDataProcess.h"
#import "PromptInfoView.h"
#import "MJRefresh.h"
#import "BulidingModel.h"
#import "FloorsModel.h"
#import "roomsModel.h"
#import "faveriterCard.h"
#import "StartPageController.h"
#import "checkPower.h"
#import "BulidingInfoLogic.h"
#import "FloorsInfoLogic.h"
#import "RoomInfoLogic.h"
#import "MJExtension.h"
#import "ChineseInclude.h"
#import "ZYPinYinSearch.h"
#import "RoomCardDataProcess.h"
#import "CardDataProcess.h"
#import "TreeGroupCell.h"
#import "TreeItemCell.h"
#import "GenerateQRCardController.h"
#import "AllocateBulidingModel.h"
#import "AllocateFloorModel.h"
#import "ItemModel.h"
#import "RoomsModel.h"
#import "NoInfoPromtView.h"
@interface CommonCardViewController ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,NoInfoPromtViewDelegate>
{
    CardInfoModel * cardInfoModel;
}

@property (nonatomic,strong) UITableView * cardTableView;
@property (nonatomic,strong) NSMutableArray * cardInfoMutArray;
@property (nonatomic,strong) NSMutableArray * totalArray;

@property (nonatomic,strong) NSMutableArray * treeArray;
@property (nonatomic,strong) NSMutableArray * buildArray;
@property (nonatomic,strong) NSMutableArray * displayDataArray;
@property (nonatomic,strong) UIButton * searchBtn;
@property (nonatomic,strong) UIButton * changeBtn;
@property (nonatomic,strong) UISearchBar * nameSearchBar;
@property (nonatomic,strong) UIImageView * cancelImgView;//取消搜索

@property (nonatomic,strong) NSUserDefaults * userInfo;
@property (nonatomic,strong) QRSingleton * singleton;
@property (nonatomic,copy) NSString * communityId;
@property (nonatomic,copy) NSString * bulidingName;
@property (nonatomic,copy) NSString * floorName;
@property (nonatomic,copy) NSString * bulidingId;
@property (nonatomic,copy)   NSString * rightBuildId;
@property (nonatomic,copy) NSString * floorId;
@property (nonatomic,copy)   NSString * rightFloorId;
@property (nonatomic,strong) UIImageView * promtBackImgView;//没有房间的提示页面
@property (nonatomic,copy) NSString * communityRole;
@property (nonatomic,assign) BOOL pattern;  //展示模式，1为所有房卡模式，0为树状模式
@property (nonatomic,assign) BOOL haveCommunityFlag;//是否有集群
@property (nonatomic,assign) BOOL comeFlag;//no切换页面过来 yes选择楼层过来的
@property (nonatomic,strong) NoInfoPromtView * noInfoPromtView;
@property (nonatomic,strong)CardDataProcess * dataProcess;

@end

@implementation CommonCardViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColorFromRGB(0xebebeb);
    self.navigationItem.title = @"常用";
    _userInfo = [NSUserDefaults standardUserDefaults];
    _singleton = [QRSingleton sharedQRSingleton];
    _cardInfoMutArray = [NSMutableArray array];
    _totalArray = [NSMutableArray array];
    _treeArray = [NSMutableArray array];
    _displayDataArray = [NSMutableArray array];
    _buildArray = [NSMutableArray array];
    _dataProcess = [[CardDataProcess alloc] init];
    cardInfoModel = [[CardInfoModel alloc]init];
    _pattern = 1;
    _comeFlag = NO;
    _haveCommunityFlag = NO;
    _changeBtn.hidden = YES;
    [self prepareCommunityData];
    [self prepareNaviBar];
    [self prepareTableView];
    [self prepareNoDataView];
}

-(void)viewWillAppear:(BOOL)animated{
    _searchBtn.hidden = NO;
    _changeBtn.hidden = NO;

}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if (![_communityId isEqualToString:_singleton.communityId] || _communityId == nil)
    {
        _communityId = _singleton.communityId;
        if (!_comeFlag) {
            _bulidingId = @"";
            _floorId = @"";
            _comeFlag = NO;
        }
        [self getDataFromDisk];
        [self prepareCommunity];
        
    }
    else
    {
        [self getDataFromDisk];
    }
    [_cardTableView reloadData];
    
}

- (void)viewWillDisappear:(BOOL)animated{
    _searchBtn.hidden = YES;
    _changeBtn.hidden = YES;
    _nameSearchBar.hidden = YES;
    _nameSearchBar.text = @"";
    _cancelImgView.hidden = YES;
}



-(void)prepareCommunityData{
    if ([self IsHaveNetwork]) {
        return;
    }
    RequestNetWork * rnk = [[RequestNetWork alloc]init];
    _communityId = [QRSingleton sharedQRSingleton].communityId;
    _singleton = [QRSingleton sharedQRSingleton];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:[_userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:_communityId forKey:@"communityId"];
    [postDict setValue:[_userInfo objectForKey:@"token"] forKey:@"token"];
    __weak CommonCardViewController * weakSelf = self;
    [self startWaiting:nil color:nil addToView:self.view];
    [rnk initWithPath:POST(HOTELINFO) params:postDict block:^(id downLoadData, id error)
     {
         NSArray * data = [downLoadData objectForKey:@"data"];
         if (data) {
             if (_pattern) {
                 [_cardInfoMutArray removeAllObjects];
                  NSArray * cardInfoArray = data;
                  if (cardInfoArray.count > 0)
                  {
                      [self deleteRooms];
                      [weakSelf insertDataIntoRooms:cardInfoArray];
                      [weakSelf analysisHouseData:cardInfoArray];
                      NSMutableDictionary * dict = [OpertionPlist readDataFromPlist];
                      [dict setValue:data forKey:HOUSEINFO];
                      [OpertionPlist writeDataToPlist:dict];
                      _totalArray = [_cardInfoMutArray mutableCopy];
                  }
                 if (_cardInfoMutArray.count == 0)
                 {
                     _noInfoPromtView.hidden = NO;
                     
                 }
             }else{
                 [_treeArray removeAllObjects];
                 [_buildArray removeAllObjects];
                 [_displayDataArray removeAllObjects];
                 _treeArray = [[_dataProcess dataProcess:data] mutableCopy];
                 _buildArray = [_treeArray mutableCopy];
                 _displayDataArray = [_treeArray mutableCopy];
                 if (_treeArray.count == 0)
                 {
//                     [PromptInfoView showMessage:NSLocalizedString(@"noRoomInfo", nil)];
                     _noInfoPromtView.hidden = NO;
                 }

             }

             
             
         }
         else if (error != nil)
         {
             if ([[error objectForKey:@"status"]intValue] == 211)
             {
                 [PromptInfoView showMessage:NSLocalizedString(@"addCommunity", nil)];
             }
             else if([[error objectForKey:@"status"]intValue] != 301)
             {
                 [PromptInfoView showMessage:[error objectForKey:@"info"]];
                 
             }
             if ([[error objectForKey:@"status"]intValue] == 301) {
                 [self deleteRooms];
                 [_cardInfoMutArray removeAllObjects];
//                 _noInfoPromtView.hidden = NO;
                 [PromptInfoView showMessage:[error objectForKey:@"info"]];
             }
             NSMutableDictionary * dict = [OpertionPlist readDataFromPlist];
             [dict setValue:data forKey:HOUSEINFO];
             [OpertionPlist writeDataToPlist:dict];
             NSLog(@"数据错误error = %@",error);
         }

         [_cardTableView reloadData];

     }];
    [self stopWaiting];

}


-(void)prepareCommunity
{
    if ([self IsHaveNetwork]) {
        return;
    }
    checkPower * power = [[checkPower alloc]init];
    [power getUserPower];
    power.powerBlock = ^(id data,id error)
    {
        if (error != nil)
        {
            if ([[error objectForKey:@"status"]integerValue] == 210)
            {
                NSMutableDictionary * communityData = [[NSMutableDictionary alloc]initWithObjectsAndKeys:nil,COMMUNITYINFOFORKEY,nil];//没有集群的时候
                [OpertionPlist writeDataToPlist:communityData];
                [PromptInfoView showMessage:[error objectForKey:@"info"]];
            }
            else
            {
                [PromptInfoView showMessage:[error objectForKey:@"info"]];
            }
        }
        else  if (data != nil)
        {
            NSDictionary * CommunityData = [data objectForKey:@"data"];
            NSArray * communityArr = [CommunityData objectForKey:@"communities"];
            if (communityArr.count > 0) {
                for (NSDictionary * dict in communityArr)
                {
                    if ([[dict objectForKey:@"communityid"]isEqualToString:_communityId])
                    {
                        _communityRole = [dict objectForKey:@"role"];
                        _haveCommunityFlag = YES;
                    }
                }
                if (!_haveCommunityFlag) {
                    _communityId = [communityArr[0] objectForKey:@"communityid"];
                    [QRSingleton sharedQRSingleton].communityId = _communityId;
                    [QRSingleton sharedQRSingleton].communityName = [communityArr[0] objectForKey:@"communityname"];
                    _haveCommunityFlag = NO;
                }
            }
            else
            {
                return;
            }
            [self prepareCommunityData];
        }

    };
}

-(void)getDataFromDisk
{
    [_cardInfoMutArray removeAllObjects];
    BulidingInfoLogic * bulidingDataBase = [[BulidingInfoLogic alloc]init];
    FloorsInfoLogic * floorDataBase = [[FloorsInfoLogic alloc]init];
    RoomInfoLogic * roomDataBase = [[RoomInfoLogic alloc]init];
    __block NSMutableArray * buildMutArray = [NSMutableArray array];
    [self startWaiting:nil color:nil addToView:self.view];
    [bulidingDataBase queryBulidingInfo:_communityId block:^(NSMutableArray *bulidingArray) {
        buildMutArray = [bulidingArray copy];
    }];
    
    for (BulidingModel * bmodel in buildMutArray) {
        [floorDataBase queryFloorsInfo:bmodel.buildingId block:^(NSMutableArray *arr) {
            bmodel.floors = [arr copy];
        }];
    }
    for (BulidingModel * bmodel in buildMutArray) {
        for (FloorsModel * fmodel in bmodel.floors) {
            [roomDataBase queryRoomInfo:fmodel.floorId block:^(NSMutableArray *roomArray) {
                for (RoomsModel * rModel in roomArray) {
                    CardInfoModel * cardModel = [[CardInfoModel alloc]init];
                    cardModel.bulidingName = bmodel.buildingName;
                    cardModel.bulidingId = bmodel.buildingId;
                    cardModel.floorName = fmodel.floorName;
                    cardModel.floorId = fmodel.floorId;
                    cardModel.roomId = rModel.roomId;
                    cardModel.roomName = rModel.roomName;
                    [_cardInfoMutArray addObject:cardModel];
                }
            }];
        }
    }
    [self stopWaiting];
}

-(void)insertDataIntoRooms:(NSArray *)allBuildingInfo
{
    BulidingInfoLogic * bulidingDataBase = [[BulidingInfoLogic alloc]init];
    FloorsInfoLogic * floorDataBase = [[FloorsInfoLogic alloc]init];
    RoomInfoLogic * roomDataBase = [[RoomInfoLogic alloc]init];
    for (NSDictionary * bDict in allBuildingInfo)
    {
        BulidingModel * bModel = [[BulidingModel alloc]init];
        bModel.buildingName = [bDict objectForKey:@"buildingname"];
        bModel.buildingId = [bDict objectForKey:@"buildingid"];
        bModel.buildingNo = [bDict objectForKey:@"buildingno"];
        [bulidingDataBase insertBulidingInfo:bModel withCommunityId:_communityId];
        bModel.floors = [bDict objectForKey:@"floors"];
        for (NSDictionary * fDict in bModel.floors) {
            FloorsModel * fModel = [[FloorsModel alloc]init];
            fModel.floorId = [fDict objectForKey:@"floorid"];
            fModel.floorName = [fDict objectForKey:@"floorname"];
            fModel.floorNo  = [fDict objectForKey:@"floorno"];
            [floorDataBase insertFloorInfo:fModel withCommunityId:_communityId buildingId:bModel.buildingId];
            fModel.rooms = [fDict objectForKey:@"rooms"];
            for (NSDictionary * rDict in fModel.rooms) {
                RoomsModel * rModel = [[RoomsModel alloc]init];
                rModel.roomId = [rDict objectForKey:@"roomid"];
                rModel.roomName = [rDict objectForKey:@"roomname"];
                rModel.roomNo = [rDict objectForKey:@"roomno"];
                rModel.isSelect = [rDict objectForKey:@"isSelected"];
                rModel.lockNo = [rDict objectForKey:@"lockno"];
                rModel.occupation = [rDict objectForKey:@"occupation"];
                [roomDataBase insertRoomInfo:rModel withFloorId:fModel.floorId withCommunityId:_communityId];
            }
        }
    }
}

-(void)deleteRooms
{
    BulidingInfoLogic * bulidingDataBase = [[BulidingInfoLogic alloc]init];
    [bulidingDataBase deleteBulidingWithCommunityId:_communityId];
    FloorsInfoLogic * floorDataBase = [[FloorsInfoLogic alloc]init];
    [floorDataBase deleteFloorsInfoWithCommunityId:_communityId];
    RoomInfoLogic * roomDataBase = [[RoomInfoLogic alloc]init];
    [roomDataBase deleteRoomWithCommunityId:_communityId];
    _bulidingId = @"";
    _bulidingName = nil;
    _floorId = @"";
    _floorName = nil;
}

-(void)analysisHouseData:(NSArray *)data
{
    if (data.count>0) {
        for (NSDictionary * dict in data) {
            BulidingModel * bmodel = [[BulidingModel alloc]init];
            bmodel.buildingId = [dict objectForKey:@"buildingid"];
            bmodel.buildingName = [dict objectForKey:@"buildingname"];
            bmodel.floors = [dict objectForKey:@"floors"];
            _bulidingName = bmodel.buildingName;
            if (bmodel.floors) {
                for (NSDictionary * fdict in bmodel.floors) {
                    FloorsModel * fmodel = [[FloorsModel alloc]init];
                    fmodel.floorId = [fdict objectForKey:@"floorid"];
                    fmodel.floorName = [fdict objectForKey:@"floorname"];
                    fmodel.rooms = [fdict objectForKey:@"rooms"];
                    _floorName = fmodel.floorName;
                    if (fmodel.rooms) {
                        for (NSDictionary * rdict in fmodel.rooms) {
                            RoomsModel * rmodel = [[RoomsModel alloc]init];
                            rmodel.roomId = [rdict objectForKey:@"roomid"];
                            rmodel.roomName = [rdict objectForKey:@"roomname"];
                            CardInfoModel * cardModel = [[CardInfoModel alloc]init];
                            cardModel.bulidingName = _bulidingName;
                            cardModel.floorName = _floorName;
                            cardModel.roomName = rmodel.roomName;
                            cardModel.roomId = rmodel.roomId;
                            cardModel.floorId = fmodel.floorId;
                            cardModel.bulidingId = bmodel.buildingId;
                            cardModel.cardStyle = 2;
                            [_cardInfoMutArray addObject:cardModel];
                            
                        }

                    }
                    
                }
            }
        }

    }
}


- (void)prepareNaviBar{
    
    _searchBtn = [[UIButton alloc] initWithFrame:CGRectMake(UI_SCREEN_WIDTH-70, 14, 16, 16)];
    [_searchBtn setBackgroundImage:[UIImage imageNamed:@"ic_search"] forState:UIControlStateNormal];
    [_searchBtn addTarget:self action:@selector(searchCard) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:_searchBtn];

    
    _changeBtn = [[UIButton alloc] initWithFrame:CGRectMake(UI_SCREEN_WIDTH-32, 14, 16, 16)];
    [_changeBtn setBackgroundImage:[UIImage imageNamed:@"fold-white"] forState:UIControlStateNormal];
    [_changeBtn addTarget:self action:@selector(changePattern) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:_changeBtn];
    
    
    _nameSearchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH - 60, 44)];
    _nameSearchBar.hidden = YES;
    _nameSearchBar.delegate = self;
    _nameSearchBar.placeholder = NSLocalizedString(@"roomNo", nil);
    _nameSearchBar.backgroundColor = RGBA(192, 191, 196, 1);
    [self.navigationController.navigationBar addSubview:_nameSearchBar];
    

    _cancelImgView = [[UIImageView alloc]initWithFrame:CGRectMake(UI_SCREEN_WIDTH-60, 0, 60, 44)];
    _cancelImgView.userInteractionEnabled = YES;
    _cancelImgView.hidden = YES;
    _cancelImgView.backgroundColor = RGBA(192, 191, 196, 1);
    [self.navigationController.navigationBar addSubview:_cancelImgView];
    
    UILabel * cancelSearchLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 12, 60, 20)];
    cancelSearchLabel.text = NSLocalizedString(@"alterCancel", nil);
    cancelSearchLabel.font = [UIFont systemFontOfSize:16.0];
    cancelSearchLabel.textAlignment = NSTextAlignmentCenter;
    [_cancelImgView addSubview:cancelSearchLabel];
    
    UITapGestureRecognizer * cancelSearchTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(cancelSearchClick)];
    [_cancelImgView addGestureRecognizer:cancelSearchTap];

}

-(void)cancelSearchClick
{
    _nameSearchBar.hidden = YES;
    _cancelImgView.hidden = YES;
    _nameSearchBar.text = @"";
    self.navigationItem.title = NSLocalizedString(@"card", nil);
    if (_pattern) {
        _cardInfoMutArray = [_totalArray mutableCopy];
    }else{
        _displayDataArray = [_treeArray mutableCopy];
        _buildArray = [_treeArray mutableCopy];
    }
    
    [_cardTableView reloadData];
    [_nameSearchBar resignFirstResponder];
}

- (void)searchCard{
    _nameSearchBar.hidden = NO;
    _cancelImgView.hidden = NO;
    self.navigationController.title = @"";
}

#pragma mark - 显示页面切换
- (void)changePattern{
    if (_pattern) {
        [_changeBtn setBackgroundImage:[UIImage imageNamed:@"spread-white"] forState:UIControlStateNormal];
    }else{
        [_changeBtn setBackgroundImage:[UIImage imageNamed:@"fold-white"] forState:UIControlStateNormal];
    }
    _pattern = !_pattern;
    [self prepareCommunityData];

}

- (void)prepareTableView{
    _cardTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_SCREEN_HEIGHT-64-49-44-16)];
    _cardTableView.backgroundColor = [UIColor clearColor];
    _cardTableView.dataSource = self;
    _cardTableView.delegate = self;
    [self.view addSubview:_cardTableView];
    
    UIView * headerVeiw = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, 16)];
    headerVeiw.backgroundColor = UIColorFromRGB(0xebebeb);
    UIView * lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 15.5, UI_SCREEN_WIDTH, 0.5)];
    lineView.backgroundColor = UIColorFromRGB(0xc1c1c1);
    [headerVeiw addSubview:lineView];
    _cardTableView.tableHeaderView = headerVeiw;
    UIView * footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, 0.5)];
    footerView.backgroundColor = UIColorFromRGB(0xc1c1c1);
    _cardTableView.tableFooterView = footerView;
    
     //设置分割线间距
    if([_cardTableView respondsToSelector:@selector(setSeparatorInset:)]){
        [_cardTableView setSeparatorInset:UIEdgeInsetsMake(0, 16, 0, 0)];
    }
    if([_cardTableView respondsToSelector:@selector(setLayoutMargins:)]){
        [_cardTableView setLayoutMargins:UIEdgeInsetsMake(0, 16, 0, 0)];
    }
    
    [_cardTableView registerNib:[UINib nibWithNibName:@"TotalCardCell" bundle:nil] forCellReuseIdentifier:@"totalCardCell"];
}

- (void)prepareNoDataView{
    float x = 0;
    float y = 0;
    float width = UI_SCREEN_WIDTH;
    float height = self.view.frame.size.height;
    _noInfoPromtView = [[NoInfoPromtView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    //    [promtView prepareViewWithPromtTitle:NSLocalizedString(@"noFunctionCard", nil)];
    [_noInfoPromtView prepareViewWith:@"noinformation_dark" withPromt:NSLocalizedString(@"noRoomInfo", nil)];
    _noInfoPromtView.hidden = YES;
    _noInfoPromtView.delegate = self;
    [self.view addSubview:_noInfoPromtView];

}

#pragma mark -- searchDelegate
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if (_pattern){
        
        [_cardInfoMutArray removeAllObjects];
        if (searchText.length==0) {
            _cardInfoMutArray = [_totalArray mutableCopy];
            [_cardTableView reloadData];
        }else{
            if (![ChineseInclude isIncludeChineseInString:searchBar.text])  //输入英文
            {
                _cardInfoMutArray = [NSMutableArray arrayWithArray: [ZYPinYinSearch searchWithOriginalArray:_totalArray andSearchText:searchBar.text andSearchByPropertyName:@"roomName"]];
                [_cardTableView reloadData];
                
            }else
            {
                for (CardInfoModel * model in _totalArray) {
                    if (([model.roomName rangeOfString:searchBar.text].location != NSNotFound))
                    {
                        [_cardInfoMutArray addObject:model];
                    }
                }
                [_cardTableView reloadData];
            }
        }
        if (_cardInfoMutArray.count == 0) {
            [PromptInfoView showMessage:NSLocalizedString(@"noSearch", nil)];
        }

    }
    else{ //折叠视图的搜索
        [_displayDataArray removeAllObjects];
        [_buildArray removeAllObjects];
        if (searchText.length==0) {
            _displayDataArray = [_treeArray mutableCopy];
            _buildArray = [_treeArray mutableCopy];
            [_cardTableView reloadData];
        }else{
            if (![ChineseInclude isIncludeChineseInString:searchBar.text]){
                NSMutableArray * bulidingArray = [[NSMutableArray alloc]init];
                NSMutableArray * floorArray = [[NSMutableArray alloc]init];
                NSMutableArray * roomArray = [[NSMutableArray alloc]init];
                for (ItemModel * bmodel in _treeArray){
                    if (bmodel.itemChildrenArray) {
                        [floorArray removeAllObjects];
                        for (ItemModel * fmodel in bmodel.itemChildrenArray) {
                            if (fmodel.itemChildrenArray) {
                                [roomArray removeAllObjects];
                                roomArray = [NSMutableArray arrayWithArray: [ZYPinYinSearch searchWithOriginalArray:fmodel.itemChildrenArray andSearchText:searchText andSearchByPropertyName:@"roomName"]];
                                if (roomArray.count > 0) {
                                    [floorArray addObject:fmodel];
                                }
                            }
                            
                        }
                        if (floorArray.count > 0) {
                            [bulidingArray addObject:bmodel];
                        }
                    }
                }
                _displayDataArray = [bulidingArray mutableCopy];
                _buildArray = [bulidingArray mutableCopy];
                
            }else{
                NSMutableArray * bulidingArray = [[NSMutableArray alloc]init];
                NSMutableArray * floorArray = [[NSMutableArray alloc]init];
                NSMutableArray * roomArray = [[NSMutableArray alloc]init];
                for (ItemModel * bmodel in _treeArray){
                    if (bmodel.itemChildrenArray) {
                        [floorArray removeAllObjects];
                        for (ItemModel * fmodel in bmodel.itemChildrenArray) {
                            if (fmodel.itemChildrenArray) {
                                [roomArray removeAllObjects];
                                for (RoomsModel * rmodel in fmodel.itemChildrenArray) {
                                    if (([rmodel.roomName rangeOfString:searchBar.text].location != NSNotFound)) {
                                        [roomArray addObject:rmodel];
                                    }
                                }
                                if (roomArray.count > 0) {
                                    [floorArray addObject:fmodel];
                                }
                            }
                            
                        }
                        if (floorArray.count > 0) {
                            [bulidingArray addObject:bmodel];
                        }
                    }
                }
                _displayDataArray = [bulidingArray mutableCopy];
                _buildArray = [bulidingArray mutableCopy];
            }
            [_cardTableView reloadData];
        }
        
    }
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
}


#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (_pattern) {
       
        return _cardInfoMutArray.count;
    }else{
       
        return _displayDataArray.count;
    }
   
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (_pattern) {
        
        NSString * ID = @"totalCardCell";
        TotalCardCell * cell = [tableView dequeueReusableCellWithIdentifier:ID];
        [_cardTableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
        if (!cell) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"TotalCardCell" owner:nil options:nil] firstObject];
            cell.backgroundColor = [UIColor whiteColor];
        }
        if (_cardInfoMutArray.count > indexPath.row) {
            CardInfoModel * model = _cardInfoMutArray[indexPath.row];
            cell.roomLabel.text = model.roomName;
            cell.floorLabel.text = model.floorName;
            [cell.floorLabel sizeToFit];
            cell.buildLabel.text = model.bulidingName;
            [cell.buildLabel sizeToFit];
        }
        return cell;
        
    }else{
        
        RoomBaseModel * nextModel  = nil;
        if (_displayDataArray.count - 1 > indexPath.row) {
            nextModel = _displayDataArray[indexPath.row + 1];
        }
        RoomBaseModel * model = [_displayDataArray objectAtIndex:indexPath.row];
        if (model.nodeType == NodeTypeGroup) {
            TreeGroupCell *cell = [TreeGroupCell cellWithTableView:tableView];
            [_cardTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
            [cell setData:(ItemModel *) model];
            return cell;
        }
        else
        {
            TreeItemCell *cell = [TreeItemCell cellWithTableView:tableView];
            [_cardTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
            [cell setData:(RoomsModel *)model];
            if (indexPath.row == _displayDataArray.count - 1) {
                cell.isLastRow = YES;
            }
            else if(nextModel.nodeLevel == 1 && model.nodeLevel == 3)
            {
                cell.isLastRow = YES;
            }
            else
            {
                cell.isLastRow = NO;
            }
            return cell;
        }

    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_pattern) {
        CardInfoModel * model = [[CardInfoModel alloc]init];
        model = _cardInfoMutArray[indexPath.row];
        model.communityid = [QRSingleton sharedQRSingleton].communityId;
        GenerateQRCardController * gvc = [[GenerateQRCardController alloc]initWithCardModel:model];
        gvc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:gvc animated:YES];
        [_cardTableView deselectRowAtIndexPath:[_cardTableView indexPathForSelectedRow] animated:YES];
        
    }else{
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        RoomBaseModel * model = _displayDataArray[indexPath.row];
        if (model.nodeLevel == 3) {
            RoomsModel * roomsModel = (RoomsModel *)model;
            cardInfoModel.communityid = [QRSingleton sharedQRSingleton].communityId;
            cardInfoModel.roomId = roomsModel.roomId;
            cardInfoModel.roomName = roomsModel.roomName;
             GenerateQRCardController * gvc = [[GenerateQRCardController alloc]initWithCardModel:cardInfoModel];
            gvc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:gvc animated:YES];
            [_cardTableView deselectRowAtIndexPath:[_cardTableView indexPathForSelectedRow] animated:YES];
        }
        model.isExpanded = !model.isExpanded;
        model.isClick = YES;
        if (model.nodeLevel == 2) {
            ItemModel * fModel = _displayDataArray[indexPath.row];
            cardInfoModel.floorId = fModel.itemId;
            cardInfoModel.floorName = fModel.itemName;
        }
        if (model.nodeLevel == 1) {
            ItemModel * bModel = _displayDataArray[indexPath.row];
            cardInfoModel.bulidingId = bModel.itemId;
            cardInfoModel.bulidingName = bModel.itemName;
        }
        [self reloadDisplayArray];
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 56;
}

#pragma mark --------点击刷新
-(void)reloadDisplayArray
{
    NSMutableArray * tmpList = [[NSMutableArray alloc]init];
    for (ItemModel * model in _buildArray) {
        if (model.isExpanded) {
            [self addData:model toArray:tmpList];
        }
        else
        {
            [tmpList addObject:model];
        }
    }
    _displayDataArray = [[NSArray arrayWithArray:tmpList] mutableCopy];
    [_cardTableView reloadData];
}

-(void)addData:(ItemModel *)model toArray:(NSMutableArray *)tmpList
{
    [tmpList addObject:model];
    for (ItemModel * floorModel in model.itemChildrenArray) {
        [tmpList addObject:floorModel];
        if (floorModel.isExpanded) {
            for (RoomsModel * roomModel in floorModel.itemChildrenArray) {
                [tmpList addObject:roomModel];
            }
        }
    }
}

- (void)clickRefresh{
    [self prepareCommunityData];
}


#pragma mark - tableViewDelegate 分割线间距
- (void)tableView:(UITableView*)tableView willDisplayCell:(UITableViewCell*)cell forRowAtIndexPath:(NSIndexPath*)indexPath{
    
    if([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        
        [cell setSeparatorInset:UIEdgeInsetsMake(0, 16, 0, 0)];
        
    }
    
    if([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        
        [cell setLayoutMargins:UIEdgeInsetsMake(0, 16, 0, 0)];
        
    }
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
